/*
 * Copyright (c) 2022 Huawei Device Co., Ltd.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

import java.nio.ByteBuffer;

class Takecolor {
    public static void picColorFromBuffer(EData e) {
        Data data = e.data;
        if(data == null || data.data == null) {
            System.out.println("dingwen input error");
            return;
        }
        String msgType = data.type;
        ByteBuffer readBuffer = data.data;
        int len = data.len / 4;
        switch (msgType) {
            case "pickColor":
                byte[] intBuffer = readBuffer.array();
                int r = 0;
                int g = 0;
                int b = 0;
                int a = 0;
                for (int i = 0; i < len; i++) {
                    r += intBuffer[i * 4];
                    g += intBuffer[i * 4 + 1];
                    b += intBuffer[i * 4 + 2];
                    a += intBuffer[i * 4 + 3];
                }
                r = Math.round((float) r / len);
                g = Math.round((float) g / len);
                b = Math.round((float) b / len);
                a = Math.round((float) a / len);
                //System.out.println("Takecolor pinColorFormBuffer color[ARGB] :\t" + a + "\t" + r + "\t" + g + "\t" + b);
                break;
            default:
                break;
        }

    }
}


class Data {
    public String type;
    public ByteBuffer data;
    public int len;
    Data(String mType, ByteBuffer mData, int mLen) {
        this.type = mType;
        this.data = mData;
        this.len = mLen;
    }
}
class EData {
    public Data data;
    EData(Data mData) {
        this.data = mData;
    }
}

/*
 * @State
 * @Tags Jetstream2
 */
class Benchmark {

    /*
     *@Benchmark
     */
    public void run() {
        ByteBuffer readBuffer = ByteBuffer.allocate(500 * 500);
        byte[] uint8Array = readBuffer.array();
        for(int i = 0; i < uint8Array.length; i++) {
            uint8Array[i] = (byte)(i % 256);
        }
        Data data = new Data("pickColor", readBuffer, 500 * 500);
        EData eData = new EData(data);
        final long start = System.nanoTime();
        for(int i = 0; i < 10; i++) {
            Takecolor.picColorFromBuffer(eData);
        }
        final long end = System.nanoTime();
        System.out.println("Takecolor_Obj: " + (double)(end - start) / 1000000 + "\tms");
    }

    public static void main(String[] args) {
        new Benchmark().run();
    }
}